package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.medical.domain.LargePositive;
import org.brisling.medical.domain.MedicalRecipel;
import org.brisling.medical.service.LargePositiveService;
import org.brisling.medical.service.RecipelService;
import org.brisling.medical.vo.VOQueryLargePositive;
import org.brisling.sysman.domain.VOJobUser;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.brisling.sysman.queryService.QueryPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryLargePositiveService</p>
 * <p>Description: 大型检查阳性率监控查询service</p>
 * <p>Company: tongking</p>
 * @author shura
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午10:06:38
 */
@RestController
@RequestMapping("/largePositive/query")
public class QueryLargePositiveService extends AbstractBaseQueryService<LargePositive>{
	
	@Autowired
	private QueryDictionaryService dicService;
	@Autowired
	private RecipelService qrService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	@Autowired
	private	LargePositiveService largePositiveService;
	
	@Autowired
	private QueryPermissionService qryPermissionService;
	
	public QueryLargePositiveService(){
		this.moduleName = ConstSysParam.MODULE_LARGE_POSITIVE;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = this.getTableName(LargePositive.class);
		this.clazz = LargePositive.class;
		typeMap = this.getTypeMap(clazz);
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<LargePositive> getListDomain(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="condition",required=false) String condition,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(condition!=null){
			String whereCorse=String.format(sb.append("deptid = %1$s").toString(),condition);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedListDomain(page,rows,sql);
	}
	
	@RequestMapping("/getList.action")
	public List<LargePositive> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public LargePositive getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public LargePositive getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	
	/**
	 * 统计大型阳性率检查指标数据
	 * @param body
	 * @return
	 */
	@RequestMapping("/getLargePositiveListDomain.action")
      public ListDomain<LargePositive> getAllListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		//查询表 
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	
    /**
     * 大额住院费用弹窗
     */
	
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_large_positive")){
			if(!isManageJob(userid)){				
				_page="popDetail";
			}					
		}
		return new ModelAndView("/medical/medical_large_positive/"+_page);
	}
	
	/**
	 * 根据传入的数据字典和ID，查询符合条件的sql语句的OneDomain
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("/getSqlOneDomain.action")
	public ListDomain<LargePositive> getSqlOneDomain(@RequestBody(required=false)String body){	
		
		Map<String,Object> conditionMap =getBodyParam(body);
		String sql=dicService.getSqlByBizcode("doct_large_positive_indicator");
		return super.getListDomainByConditionAndOrder(sql, conditionMap, typeMap, orderMap, false);
	}
	
	
	
	/**
	 * 自动发送质询记录
	 * @param userId
	 */
	public void autosave (String userId){
		List <VOQueryLargePositive> lists = this.getLargePositive("inquiry_large_positive");
		if (lists != null){
			for (VOQueryLargePositive e : lists){
				MedicalRecipel tmp = this.LargePositiveToMedicalRecipel(e);
				if (tmp==null) continue;
				qrService.completeTask(userId, tmp);
			}
		}
	}
	
	/**
	 * 自动统计
	 */
	public void autoTask(){
		Integer year=null;
		Integer month=null;
		this.autoUpdate(year, month);
	}
	
	
	/**
	 * 自动更新指标数据
	 * @param month
	 * @param year
	 */
	public void autoUpdate(Integer year, Integer month){
		String[] yestodayMonth=null ;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		LargePositive largePositive = getYestedayLargePositive(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1]);
		LargePositive oldLargePositive=super.getOneByIdentify("monitor_year_month", yestodayMonth[2]);
		if(oldLargePositive.getId()!=null){
			largePositive.setId(oldLargePositive.getId());
		}
		if(largePositive!=null){
			largePositive.setMonitor_year_month(yestodayMonth[2]);
			largePositiveService.save(largePositive);
		}
		
	}
	

	/**
	 * 自动更新指标数据
	 * @param month
	 * @param year
	 */
	/*
	public List <LargePositive> autoUpdate(Integer year, Integer month){
		String[] yestodayMonth=null ;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		
		//按全院、部门、医生统计大型阳性率指标信息
		List<LargePositive> inlists = countLargePositive(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1]);
		
		//查询已有数据
		List<LargePositive> oldLists = this.getList(yestodayMonth[2]);
		LinkedHashMap<String,LargePositive> lmap = new LinkedHashMap<String,LargePositive>();
		//将已有值存入临时map
		if(oldLists!=null && oldLists.size()>0){
			for(int i=0;i<oldLists.size();i++){
				LargePositive b = oldLists.get(i);
				String _key = null;
				if(b.getDoct_code()==null ){
					_key = b.getDept_code().toString();
				}else{
					_key = b.getDept_code() +"-" + b.getDoct_code();
				}
				lmap.put(_key, b);
			}
		}
		if(inlists!=null ){
			
			if(lmap!=null && lmap.size()>0){
				for(int i=0;i<inlists.size();i++){
					LargePositive b = inlists.get(i);
					String _key = null;
					if(b.getDoct_code()==null ){
						_key = b.getDept_code().toString();
					}else{
						_key = b.getDept_code() +"-" + b.getDoct_code();
					}
					if(lmap.containsKey(_key)){
						inlists.get(i).setId(lmap.get(_key).getId());
					}
					if(inlists.get(i).getMonitor_year_month()==null)
						inlists.get(i).setMonitor_year_month(yestodayMonth[2]);
				}
			}
			
					
		}	
		return inlists;	
		
		
//		LargePositive largePositive = getYestedayLargePositive(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1]);
//		LargePositive oldLargePositive=super.getOneByIdentify("monitor_year_month", yestodayMonth[2]);
//		if(oldLargePositive.getId()!=null){
//			largePositive.setId(oldLargePositive.getId());
//		}
//		if(largePositive!=null){
//			largePositive.setMonitor_year_month(yestodayMonth[2]);
//			largePositiveService.save(largePositive);
//		}
		
	}
	
	*/
	
	/**
	 * 统计大额住院费用情况
	 * @param year_month
	 * @param startDate
	 * @param endDate
	 * @param countType	0,期间出院病人;1,期间在院病人
	 * @return
	 */
	public List<LargePositive> countLargePositive(String year_month,String startDate ,String endDate){
		
		
		
		//出院病人统计语句
		String[] sqlids= {"total_large_positive_indicator","depart_large_positive_indicator","doct_large_positive_indicator"};
		//统计全院数据-住院
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = dicService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		List<LargePositive> lists = super.monitorCountBase(year_month,startDate,endDate,sqls);		
		
		return lists;
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<LargePositive> getList(String monitor_year_month){
		
		String sql = String.format("select * from %1$s where monitor_year_month='%2$s'",this.tableName,monitor_year_month); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 获取上一个月大型阳性指标
	 */
	public LargePositive getYestedayLargePositive(String monitor_year_month,String startDate,String endDate){
//		String sqlids[]={"total_large_positive_indicator","depart_large_positive_indicator"};
		String sqlids[]={"total_large_positive_indicator"};
		List<String> sqls = new ArrayList<String>();
		for(int i =0;i<sqlids.length;i++){
			String sql = dicService.getSqlByBizcode(sqlids[i]);
			if(sql!=null)
				sqls.add(sql);
		}
		List<LargePositive> largePositiveList= super.monitorCountBase(monitor_year_month, startDate, endDate, sqls);
		LargePositive largePositive =new LargePositive();
		if(largePositiveList!=null){
			for(int i =0;i<largePositiveList.size();i++){
				LargePositive temp = largePositiveList.get(i);
//				if(temp.getDepart_name()!=null)
//					largePositive.setDepart_name(temp.getDepart_name());
//				if(temp.getDepart_ratio_positive()!=null){
//					largePositive.setDepart_ratio_positive(temp.getDepart_ratio_positive());
//				}
//				if(temp.getDepart_positive_num()!=null){
//					largePositive.setDepart_positive_num(temp.getDepart_positive_num());
//				}
//				if(temp.getDepart_total_num()!=null){
//					largePositive.setDepart_total_num(temp.getDepart_total_num());
//				}if(temp.getMonitor_year_month()!=null){
//					largePositive.setMonitor_year_month(temp.getMonitor_year_month());
//				}
				if(temp.getRatio_positive()!=null){
					largePositive.setRatio_positive(temp.getRatio_positive());
				}
				if(temp.getAmount_percent_standard()!=null){
					largePositive.setAmount_percent_standard(temp.getAmount_percent_standard());
				}
					
			}
		}
		return largePositive;
	}
	/**
	 * 按照部门查询阳性率
	 * @param page
	 * @param rows
	 * @param condition
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getListByDepartDomain.action")
	public ListDomain<LargePositive> getListByDepartDomain(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="condition",required=false) String condition,
			@RequestParam(value="sort",required=false) String sort){		
		
		String sqlid="depart_large_positive_indicator";
		
			String sql = dicService.getSqlByBizcode(sqlid);
		return super.getPagedListDomain(page,rows,sql);
	}
	
	/**
	 * 获取大型阳性率数据
	 * @param bizcode
	 * @return
	 */
	public List <VOQueryLargePositive> getLargePositive (String bizcode){
		String sql = dicService.getSqlByBizcode(bizcode);
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
		sql = String.format(sql, format.format((new Date().getTime() - (long)24*60*60*1000*15)).toString());
		try {
			return super.getClassedAllList(sql, VOQueryLargePositive.class);
		} catch (DangerousOperatorException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public MedicalRecipel LargePositiveToMedicalRecipel(VOQueryLargePositive list){
		String Bizcode = qryPermissionService.getBizFlowConfig("recipel").getFullBizcode();
		String flowid = qryPermissionService.getBizFlowConfig("recipel").getFlowid();
		
		MedicalRecipel mr = new MedicalRecipel();
		//质询日期
		mr.setInquiry_date(new Date());
		//质询事项
		mr.setInquiry_item("阳性率异常");
		//质询事项子类
		mr.setInquiry_item_sub("医生阳性率检查异常");
		//质询事项子类及代码
		mr.setInquiry_item_subcode("211");
		mr.setInquiry_item_code("17");
		mr.setPatient_type("2");
		List<VOJobUser> jobUsr = SysConfig.getJobUserByDept("20", list.getDoct_depart_code().toString());
		mr.setDoct_name(jobUsr.get(0).getDoct_name());
		mr.setDoct_id(jobUsr.get(0).getDoct_code().toString());
		//住院号
		if(list.getZyhm()!=null)
			mr.setZyhm(list.getZyhm());
		//科室名称
		if(list.getDoct_depart_name()!=null)
			mr.setDoct_depart_name(list.getDoct_depart_name());
		//医生科室编码
		if(list.getDoct_depart_code()!=null)
			mr.setDoct_depart_code(list.getDoct_depart_code());
		//患者id
		if(list.getPatient_id()!=null)
			mr.setPatient_id(list.getPatient_id().toString());
		//患者名字
		if(list.getPatient_name()!=null)
			mr.setPatient_name(list.getPatient_name());
		//mr.setPatient_id("3333");
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
		//test用
		mr.setFlowid(flowid);
		mr.setFullBizcode(Bizcode);
		return mr;
	}
	/**
	 * 测试用
	 * @param userId
	 */
	public void test(String userId) {
		VOQueryLargePositive temp = new VOQueryLargePositive();
		//temp.set
		MedicalRecipel tmp = this.LargePositiveToMedicalRecipel(temp);
		qrService.completeTask(userId, tmp);
	}
	
	
	
	
}

